import { message } from 'ant-design-vue'
export default class Socket {

  constructor (url, callback) {
    this.url = url
    this.callback = callback
    this.ws = null,
    this.status = 0,
    this.reConnectInterval = 3000
  }

  connect () {
    this.ws = new WebSocket(this.url)

    this.ws.onopen = () => this.status = 1
    this.ws.onclose = (e) => {
      message.error(e)
      this.status = this.status === 2 ? this.status : 0
      setTimeout(() => {
        if (this.status === 0) {
          this.connect()
        }
      }, this.reConnectInterval)
    }
    this.ws.onmessage = (e) => {
      this.callback(JSON.parse(e.data))
    }
    this.ws.onerror = (e) => {
      message.error(e)
    }
  }

  // 主动断开
  close () {
    this.status = 2
    this.ws.close()
  }

  // 发消息
  sendMessage (data) {
    this.ws.send(JSON.stringify(data))
  }
}